<template>
  <ElSelect
    :modelValue="modelValue"
    :remote="remote"
    :filterable="remote"
    :remoteMethod="remoteMethod && handleRemote"
    v-bind="attrs"
    @update:model-value="emits('update:modelValue', $event)"
  >
    <ElOption
      v-for="item in optionsDispatch"
      :key="item.value"
      :class="itemCls"
      :label="item.label"
      :value="item.value"
      :disabled="item.disabled"
    >
      <slot name="option" :data="item" />
    </ElOption>
  </ElSelect>
</template>
<script lang="ts" setup>
const props = withDefaults(
  defineProps<{
    modelValue: OptionItem["value"];
    options?: OptionItem[];
    remoteMethod?: (query?: string) => Promise<OptionItem[]>;
    itemCls?: string;
    getOptions?: () => Promise<OptionItem[]>;
  }>(),
  {
    options: () => [],
  },
);

const emits = defineEmits<{
  (e: "update:modelValue", value: OptionItem["value"]): void;
  (e: "detailChange", value?: OptionItem): void;
}>();

defineOptions({
  name: "FormSelect",
});

const attrs = useAttrs();
interface OptionItem extends Record<string, any> {
  label: string;
  value: string | number;
  disabled?: boolean;
  [key: string]: any;
}

const localOptions = ref<OptionItem[]>([]);

const remoteOptions = ref<OptionItem[]>([]);

const remote = computed(() => !!props.remoteMethod);

const localOptionsDispatch = computed(() => {
  return props.getOptions ? localOptions.value : props.options;
});

const optionsDispatch = computed(() => {
  return remote.value ? remoteOptions.value : localOptionsDispatch.value;
});

const detail = computed(() => {
  return optionsDispatch.value.find((item) => item.value === props.modelValue);
});

const handleRemote = async (query?: string) => {
  remoteOptions.value = await props.remoteMethod!(query);
};

onMounted(() => {
  if (props.remoteMethod) {
    handleRemote();
  } else {
    props.getOptions?.().then((res) => {
      localOptions.value = res;
    });
  }
});

watch(
  detail,
  (n) => {
    emits("detailChange", n);
  },
  {
    immediate: true,
  },
);
</script>
